import { MessageBox } from 'element-ui'
import { padStart } from 'lodash'
// 检测是否有更新
export async function getUpdateInfo(last_update) {
  if (localStorage.getItem('last_update') !== last_update) {
    MessageBox.alert('检测到系统有更新，请点击确定进行更新', '消息提醒', {
      type: 'warning',
      callback: () => {
        window.location.reload()
        localStorage.setItem('last_update', last_update)
      },
    })
  }
}
/**
 * @description 格式化时间
 * @param time
 * @param cFormat
 * @returns {string|null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }
  return format.replace(/{([ymdhisa])+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
}

/**
 * @description 格式化时间
 * @param time
 * @param option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

export function getDiffDays(sDate1, sDate2) {
  sDate1 = Date.parse(sDate1)
  sDate2 = sDate2 ? Date.parse(sDate2) : Date.parse(new Date())
  const timediff = (sDate1 - sDate2) / 1000

  var days = parseInt(timediff / 86400)
  //计算小时数
  var remain = timediff % 86400
  var hours = parseInt(remain / 3600)
  //计算分钟数
  remain = remain % 3600
  var mins = parseInt(remain / 60)
  return {
    days,
    hours,
    mins,
  }
}

/**
 * @description 将url请求参数转为json格式
 * @param url
 * @returns {{}|any}
 */
export function paramObj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
      '"}'
  )
}

/**
 * @description 父子关系的数组转换成树形结构数据
 * @param data
 * @returns {*}
 */
export function translateDataToTree(data) {
  const parent = data.filter(
    (value) => value.parentId === 'undefined' || value.parentId === null
  )
  const children = data.filter(
    (value) => value.parentId !== 'undefined' && value.parentId !== null
  )
  const translator = (parent, children) => {
    parent.forEach((parent) => {
      children.forEach((current, index) => {
        if (current.parentId === parent.id) {
          const temp = JSON.parse(JSON.stringify(children))
          temp.splice(index, 1)
          translator([current], temp)
          typeof parent.children !== 'undefined'
            ? parent.children.push(current)
            : (parent.children = [current])
        }
      })
    })
  }
  translator(parent, children)
  return parent
}

/**
 * @description 树形结构数据转换成父子关系的数组
 * @param data
 * @returns {[]}
 */
export function translateTreeToData(data) {
  const result = []
  data.forEach((item) => {
    const loop = (data) => {
      result.push({
        id: data.id,
        name: data.name,
        parentId: data.parentId,
      })
      const child = data.children
      if (child) {
        for (let i = 0; i < child.length; i++) {
          loop(child[i])
        }
      }
    }
    loop(item)
  })
  return result
}

/**
 * @description 10位时间戳转换
 * @param time
 * @returns {string}
 */
export function tenBitTimestamp(time) {
  const date = new Date(time * 1000)
  const y = date.getFullYear()
  let m = date.getMonth() + 1
  m = m < 10 ? '' + m : m
  let d = date.getDate()
  d = d < 10 ? '' + d : d
  let h = date.getHours()
  h = h < 10 ? '0' + h : h
  let minute = date.getMinutes()
  let second = date.getSeconds()
  minute = minute < 10 ? '0' + minute : minute
  second = second < 10 ? '0' + second : second
  return y + '年' + m + '月' + d + '日 ' + h + ':' + minute + ':' + second //组合
}

/**
 * @description 13位时间戳转换
 * @param time
 * @returns {string}
 */
export function thirteenBitTimestamp(time) {
  const date = new Date(time / 1)
  const y = date.getFullYear()
  let m = date.getMonth() + 1
  m = m < 10 ? '' + m : m
  let d = date.getDate()
  d = d < 10 ? '' + d : d
  let h = date.getHours()
  h = h < 10 ? '0' + h : h
  let minute = date.getMinutes()
  let second = date.getSeconds()
  minute = minute < 10 ? '0' + minute : minute
  second = second < 10 ? '0' + second : second
  return y + '年' + m + '月' + d + '日 ' + h + ':' + minute + ':' + second //组合
}

/**
 * @description 获取随机id
 * @param length
 * @returns {string}
 */
export function uuid(length = 32) {
  const num = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
  let str = ''
  for (let i = 0; i < length; i++) {
    str += num.charAt(Math.floor(Math.random() * num.length))
  }
  return str
}

/**
 * @description m到n的随机数
 * @param m
 * @param n
 * @returns {number}
 */
export function random(m, n) {
  return Math.floor(Math.random() * (m - n) + n)
}

/**
 * @description addEventListener
 * @type {function(...[*]=)}
 */
export const on = (function () {
  return function (element, event, handler, useCapture = false) {
    if (element && event && handler) {
      element.addEventListener(event, handler, useCapture)
    }
  }
})()

/**
 * @description removeEventListener
 * @type {function(...[*]=)}
 */
export const off = (function () {
  return function (element, event, handler, useCapture = false) {
    if (element && event) {
      element.removeEventListener(event, handler, useCapture)
    }
  }
})()

/**
 * @description 数组打乱
 * @param array
 * @returns {*}
 */
export function shuffle(array) {
  let m = array.length,
    t,
    i
  while (m) {
    i = Math.floor(Math.random() * m--)
    t = array[m]
    array[m] = array[i]
    array[i] = t
  }
  return array
}

export function getAge(birthday) {
  const birth = Number(birthday.substr(0, 4))
  const year = new Date().getFullYear()
  return year - birth
}

export function convertArr2Obj(arr, key) {
  return arr.reduce((obj, v) => {
    obj[v[key]] = v
    return obj
  }, {})
}

export function convertArr2Objs(arr, key) {
  return arr.reduce((obj, v) => {
    if (obj[v[key]]) {
      obj[v[key]].push(v)
    } else {
      obj[v[key]] = [v]
    }
    return obj
  }, {})
}

export function sum(arr) {
  return arr.reduce(function (prev, curr) {
    return prev + curr
  }, 0)
}

export function formatStrToDate(str) {
  return str.substr(0, 10)
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}

/**
 * 去除对象中值为null、undefined、''的字段
 * @param {*} obj
 * @returns
 */
export function removeEmptyField(obj) {
  var newObj = {}
  if (typeof obj === 'string') {
    obj = JSON.parse(obj)
  }
  if (obj instanceof Array) {
    newObj = []
  }
  if (obj instanceof Object) {
    for (var attr in obj) {
      if (
        Object.prototype.hasOwnProperty.call(obj, attr) &&
        obj[attr] !== '' &&
        obj[attr] !== null &&
        obj[attr] !== undefined
      ) {
        if (obj[attr] instanceof Object) {
          newObj[attr] = removeEmptyField(obj[attr])
        } else if (
          typeof obj[attr] === 'string' &&
          ((obj[attr].indexOf('{') > -1 && obj[attr].indexOf('}') > -1) ||
            (obj[attr].indexOf('[') > -1 && obj[attr].indexOf(']') > -1))
        ) {
          try {
            var attrObj = JSON.parse(obj[attr])
            if (attrObj instanceof Object) {
              newObj[attr] = removeEmptyField(attrObj)
            }
          } catch (e) {
            newObj[attr] = obj[attr]
          }
        } else {
          newObj[attr] = obj[attr]
        }
      }
    }
  }
  return newObj
}

export function getBloodApplyStatus(bloodApplyStatus) {
  const result = []
  for (var item in bloodApplyStatus) {
    const temp = bloodApplyStatus[item]
    temp.value = item
    result.push(temp)
  }
  return result.sort((a, b) => {
    return a.order - b.order
  })
}

export function getCurrentTime() {
  var today = new Date()
  var y = today.getFullYear()
  var m = today.getMonth()
  var d = today.getDate()
  var h = today.getHours()
  var i = today.getMinutes()
  var s = today.getSeconds() // 在小于10的数字钱前加一个‘0’
  m = m + 1
  d = checkTime(d)
  m = checkTime(m)
  h = checkTime(h)
  i = checkTime(i)
  s = checkTime(s)

  return [y, m, d].join('-') + ' ' + [h, i, s].join(':')
}

export function getNextTime(date, day = 14) {
  const dd = new Date(date)
  dd.setDate(dd.getDate() + day)
  const y = dd.getFullYear()
  const m =
    dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1
  const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate()
  const h = checkTime(dd.getHours())
  const i = checkTime(dd.getMinutes())
  const s = checkTime(dd.getSeconds())

  return [y, m, d].join('-') + ' ' + [h, i, s].join(':')
}

export function getCurrentDate() {
  var dd = new Date()
  return [
    dd.getFullYear(),
    (dd.getMonth() + 1).toString().padStart(2, 0),
    dd.getDate().toString().padStart(2, 0),
  ].join('-')
}

export function getNextDate(date, day = 14) {
  const dd = new Date(date)
  dd.setDate(dd.getDate() + day)
  return [
    dd.getFullYear(),
    (dd.getMonth() + 1).toString().padStart(2, 0),
    dd.getDate().toString().padStart(2, 0),
  ].join('-')
}

function checkTime(i) {
  if (i < 10) {
    i = '0' + i
  }
  return i
}

export function getAttr(formData, field) {
  let result = (formData && formData[field]) || '--'
  if (result && result.length === 0) {
    result = '--'
  }
  return result
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

export function includes(arr1, arr2) {
  return arr2.every((val) => arr1.includes(val))
}

export function getFilterBloodMatchTypeName(bloodMatchType) {
  const map = {
    1: '红细胞',
    2: '血小板',
    7: '浓缩血小板',
  }
  // if (+bloodMatchType === 1) {
  //   result = '红细胞'
  // } else if {
  //   result = '红细胞'
  // }
  return map[+bloodMatchType] || ''
}

/**
 * 字符串截取
 * @param {*} str
 * @param {*} start
 * @param {*} length
 * @returns
 */
export function substr(str, start = 0, length = 10) {
  return str.substr(start, length)
}

export function setArrayItem(key, value) {
  value = JSON.stringify(value)
  localStorage.setItem(key, value)
}

export function getArrayItem(key, initValue) {
  if (localStorage.getItem(key)) {
    try {
      return JSON.parse(localStorage.getItem(key))
    } catch (err) {
      console.log(err)
      return initValue || []
    }
  }
  return initValue || []
}

export function filterList(list, bloodMatchTypePid) {
  // return list.filter((val) => {
  //   return +val.blood_match_type_id === +bloodMatchTypePid
  // })
  return list.filter((val) => {
    if (+bloodMatchTypePid === 2) {
      return (
        (val.BLOOD_TYPE_NAME.indexOf('血小板') > -1 &&
          val.BLOOD_TYPE_NAME.indexOf('浓缩血小板') === -1) ||
        val.BLOOD_TYPE_NAME === ''
      )
    }
    if (+bloodMatchTypePid === 1) {
      return val.BLOOD_TYPE_NAME.indexOf('红细胞') > -1
    }
    if (+bloodMatchTypePid === 7) {
      return val.BLOOD_TYPE_NAME.indexOf('浓缩血小板') > -1
    }
  })
}

export function padEnd(str, n, number = 0) {
  return (str + Array(n).join(number)).slice(number, n)
}

import { bloodGroupsDict } from '@/utils/constant'
// 根据血型码解析血型和RHD
export function parseBloodGroupRhdByCode(code) {
  const res = bloodGroupsDict[code] || {}
  return {
    abo: res.group || '',
    rhd: res.rhd || '',
  }
}

// 根据血液成分码解析血液成分
export function parseBloodComponentByCode(code, bloodComponents) {
  // code = code.substr(0, 5).replace('P', '').replace('V', '').padStart(5, 'P') + 'V00'
  code = code
    .substr(0, 5)
    .replace('P', '')
    .replace('V', '')
    .padStart(5, 'P')
    .toUpperCase()
  const bloodComponentsDict = getArrayItem('bloodCodes')
  const blood_component_name = bloodComponentsDict[code] || ''
  const res = []
  if (blood_component_name) {
    const cat = blood_component_name.cat
    const name = blood_component_name.name
    bloodComponents = bloodComponents.filter((val) => {
      return val.name === cat
    })
    const bloodComponentCat = bloodComponents[0]
    const bloodComponentChildren = bloodComponentCat['children']
    const bloodComponentChildrenObj = convertArr2Obj(
      bloodComponentChildren,
      'name'
    )
    if (bloodComponentCat) {
      res.push(bloodComponentCat.id)
    }
    if (bloodComponentChildrenObj[name]) {
      res.push(bloodComponentChildrenObj[name].id)
    }
  }
  return res
}

// 根据血液失效期码解析血液失效期
export function parseBloodInvalidTimeByCode(code) {
  if (code) {
    const firstCode = code.substr(0, 1)
    if (+firstCode === 0) {
      const starttime = ['20' + code.substr(1, 2), '01', '01'].join('-')
      const days = +code.substr(3, 3) - 1
      const hours = +code.substr(6, 2)
      const minutes = +code.substr(8, 2)
      return computeDate(starttime, 'add', days, hours, minutes, 0)
    } else {
      code = code.replace('T', '')
      const year = new Date().getFullYear()
      if (code.length === 10) {
        code = year.toString().substr(0, 2) + code
      }
      const codeArr = code.replace(/(.{2})(?=.)/g, '$1 ').split(' ')
      const date = [codeArr[0] + codeArr[1], codeArr[2], codeArr[3]].join('-')
      const time = [codeArr[4], codeArr[5], '00'].join(':')
      return date + ' ' + time
    }
  }
  return ''
}

export function computeDate(times, type, days, hours, minutes, seconds) {
  let all_time = new Date().getTime()
  if (times) {
    // 全部需要减掉的时间戳
    all_time = new Date(times).getTime()
  }

  switch (type) {
    case 'add':
      all_time +=
        days * 24 * 60 * 60 * 1000 +
        hours * 60 * 60 * 1000 +
        minutes * 60 * 1000 +
        seconds * 1000
      break
    case 'minus':
      all_time -=
        days * 24 * 60 * 60 * 1000 +
        hours * 60 * 60 * 1000 +
        minutes * 60 * 1000 +
        seconds * 1000
      break
  }

  // 转换时间戳格式
  const dd = new Date(all_time)
  dd.setHours(dd.getHours() + dd.getTimezoneOffset() / 60)
  return formatDatetime(dd)

  // 转换时间戳格式
  // return formatDate(all_time)
}

export function formatDatetime(dd) {
  const m = dd.getMonth() + 1
  const d = padStart(dd.getDate(), 2, 0)
  const y = dd.getFullYear()
  const h = padStart(dd.getHours(), 2, 0)
  const i = padStart(dd.getMinutes(), 2, 0)
  const s = padStart(dd.getSeconds(), 2, 0)
  return [y, m, d].join('-') + ' ' + [h, i, s].join(':')
}

// 时间戳转换方法yyyy-MM-dd HH:mm:ss(时间戳)
export function formatDate(time) {
  const date = new Date(time)
  // date.setHours(date.getHours() + date.getTimezoneOffset() / 60)
  const YY = date.getFullYear()
  const MM =
    date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  const DD = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  const hh = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  const mm =
    date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  const ss =
    date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()

  // 这里可以修改返回的日期格式
  return YY + '-' + MM + '-' + DD + ' ' + hh + ':' + mm + ':' + ss
}

export function isNumeric(str) {
  return /^\d+$/.test(str) // 匹配一连串数字
}

export function getDiffTimes(showTime, currentTime) {
  if (!currentTime) {
    currentTime = new Date()
  } else {
    currentTime = new Date(currentTime)
  }

  const targetTime = new Date(showTime)

  // 计算时间差（以毫秒为单位）
  const timeDiff = targetTime.getTime() - currentTime.getTime()

  // console.log(currentTime, targetTime, timeDiff)
  // 将时间差转换为小时、分钟和秒数
  const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24))
  const hours = Math.floor((timeDiff / (1000 * 60 * 60)) % 24)
  const minutes = Math.floor((timeDiff / (1000 * 60)) % 60)
  const seconds = Math.floor((timeDiff / 1000) % 60)

  return { days, hours, minutes, seconds }
}

/**
 * 获取失效时间码
 * @param {*} invalid_time
 * @returns
 */
export function getInvalidCode(invalid_time) {
  const year = invalid_time.substr(0, 4)
  const time = invalid_time.substr(11)
  const days = getDayOfYear(invalid_time.substr(0, 10))
  return [
    year.substr(2).padStart(3, '0'),
    days.toString().padStart(3, '0'),
    time.replaceAll(':', '').substr(0, 4),
  ].join('')
}

/**
 * 根据日期获取当前日期在当年第几天
 * @param {*} date
 * @returns
 */
export function getDayOfYear(date) {
  date = new Date(date)
  const startOfYear = new Date(date.getFullYear(), 0, 1)
  const diff = date - startOfYear
  const oneDay = 1000 * 60 * 60 * 24
  const dayOfYear = Math.floor(diff / oneDay) + 1
  return dayOfYear
}

export function chunkArray(array, chunkSize) {
  return Array.from({ length: Math.ceil(array.length / chunkSize) }, (v, i) =>
    array.slice(i * chunkSize, i * chunkSize + chunkSize)
  )
}

/**
 * 获取配血和用血对应的是否需要标红
 * @param {*} row
 * @returns
 */
export function getMatchTransClass(row) {
  if (row.TRANS_DATE) {
    const { days } = getDiffTimes(row.TRANS_DATE_FORMAT, row.now)
    if (days < 0) {
      return 'color-danger'
    }
  } else {
    if (row.MATCH_DATE) {
      const { days } = getDiffTimes(row.MATCH_DATE_FORMAT, row.now)
      if (days <= -3) {
        return 'color-danger'
      }
    }
  }

  return ''
}

export function arraySort(arr, key, sortType = 'desc') {
  return arr.sort(function (a, b) {
    if (sortType === 'desc') {
      return b[key] - a[key]
    }
    return a[key] - b[key]
  })
}
